﻿CREATE PROCEDURE [util].[GetIndexPropertyInDbContext]
@DbName [sysname], @TableName [sysname], @IndexName [sysname], @Property NVARCHAR (128), @Value INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int
	SET @RC = 0

	DECLARE @PropertyQuery nvarchar(512)
	SET @PropertyQuery = N'
		DECLARE @ObjectId int
		SET @ObjectId = OBJECT_ID(@TableName)
		SET @Value = INDEXPROPERTY(@ObjectId, @IndexName, @Property)'

	DECLARE @QueryInDbContext nvarchar(756)
	SET @QueryInDbContext = N'EXEC [' + @DbName + '].dbo.sp_executesql
		N''' + REPLACE(@PropertyQuery,'''','''''') + '''
		,N''@TableName sysname, @IndexName sysname, @Property nvarchar(128), @Value int OUTPUT''
		,@TableName, @IndexName, @Property, @Value OUTPUT'

	EXEC @RC = dbo.sp_executesql @QueryInDbContext
		,N'@TableName sysname, @IndexName sysname, @Property nvarchar(128), @Value int OUTPUT'
		,@TableName, @IndexName, @Property, @Value OUTPUT

EXIT_PROC:
	RETURN(@RC)
END